package com.lm.netty.UdpServer;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;


/**
 * @author liuming
 */
@Slf4j
public class BootNettyUdpSimpleChannelInboundHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg){
        try {
            String data = msg.content().toString(CharsetUtil.UTF_8);
            //打印收到的消息
            log.info(data);
            //收到udp消息后，可通过此方式原路返回的方式返回消息，例如返回时间戳
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(System.currentTimeMillis()/1000+"", CharsetUtil.UTF_8), msg.sender()));
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
